package com.matrix.auth.utils;

import com.matrix.auth.config.JwtProperties;
import com.matrix.common.enums.UserTypeEnum;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 有点甜
 * @since 2025/7/25
 */
@Component
@RequiredArgsConstructor
public class JwtUtil {

    private final JwtProperties jwtProperties;

    private static final String CLAIM_KEY_USER_ID = "uid";
    private static final String CLAIM_KEY_USER_ROLE = "rol";

    public Map<String, String> generateTokenPair(Long userId, String userType) {
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("accessToken", generateAccessToken(userId, userType));
        tokenMap.put("refreshToken", generateRefreshToken(userId, userType));
        return tokenMap;
    }

    public String generateAccessToken(Long userId, String userType) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USER_ID, userId);
        claims.put(CLAIM_KEY_USER_ROLE, userType);
        return generateToken(claims, jwtProperties.getAccessSecret(), jwtProperties.getAccessTtl());
    }

    public String generateRefreshToken(Long userId, String userType) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USER_ID, userId);
        claims.put(CLAIM_KEY_USER_ROLE, userType);
        return generateToken(claims, jwtProperties.getRefreshSecret(), jwtProperties.getRefreshTtl());
    }

    private String generateToken(Map<String, Object> claims, String secret, long ttlMillis) {
        SecretKey key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Date exp = new Date(nowMillis + ttlMillis);

        return Jwts.builder()
                .claims(claims)
                .issuedAt(now)
                .expiration(exp)
                .signWith(key)
                .compact();
    }

    private Claims getClaimsFromToken(String token, String secret) {
        SecretKey key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
        return Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

    public Long getUserIdFromRefreshToken(String token) {
        return getClaimsFromToken(token, jwtProperties.getRefreshSecret()).get(CLAIM_KEY_USER_ID, Long.class);
    }

    public String getUserTypeFromRefreshToken(String token) {
        return getClaimsFromToken(token, jwtProperties.getRefreshSecret()).get(CLAIM_KEY_USER_ROLE, String.class);
    }

    public boolean isTokenExpired(String token, String secret) {
        try {
            Date expiration = getClaimsFromToken(token, secret).getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }
}
